<!--
 * @Author: 四川华西绿舍建材有限公司
 * @Date: 2024-03-12 16:40:49
 * @LastEditors: 陈波
 * @LastEditTime: 2024-03-16 22:37:39
 * @Description: 
 * @FilePath: \graDesign\src\views\SystemManagement\UserManagement\detailAndUpdate.vue
-->
<template>
  <BasicDialog
    :visible="userDialogVisible"
    width="40%"
    :title="title"
    :showClose="true"
    @handleClose="handleClose"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      v-loading="formLoading"
      status-icon
    >
      <el-form-item label="用户id:" prop="userid">
        <el-input v-model="ruleForm.userid" clearable disabled />
      </el-form-item>
      <el-form-item label="用户名:" prop="username">
        <el-input v-model="ruleForm.username" clearable :disabled="!isEdit" />
      </el-form-item>
      <el-form-item label="身份权限:" prop="ismanager">
        <el-tag v-if="ruleForm.ismanager == 2">超级管理员</el-tag>
        <el-tag v-else-if="ruleForm.ismanager == 1">管理员</el-tag>
        <el-tag v-else type="success">用户</el-tag>
      </el-form-item>
      <el-form-item label="手机号:" prop="phone">
        <el-input v-model="ruleForm.phone" clearable :disabled="!isEdit" />
      </el-form-item>
      <el-form-item label="账号状态:" prop="status">
        <el-select
          v-model="ruleForm.status"
          placeholder="请选择"
          :disabled="!isEdit"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间:" prop="createTime">
        <el-input v-model="ruleForm.createTime" clearable disabled />
      </el-form-item>
      <el-form-item label="头像:" prop="avatar">
        <div v-if="!isEdit">
          <el-image
            style="width: 100px; height: 100px;"
            :src="ruleForm.avatar"
            fit="contain"
          />
        </div>
        <div v-else>
          <el-upload
            v-model:file-list="fileList"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="1"
            :on-remove="handleRemove"
            :on-change="handleChange"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="人脸:" prop="faceBase">
        <div v-if="!isEdit">
          <el-image
            style="width: 100px; height: 100px;"
            :src="ruleForm.faceBase"
            fit="contain"
          />
        </div>
        <div v-else>
          <el-image
            style="width: 100px; height: 100px; cursor: pointer;"
            :src="ruleForm.faceBase"
            fit="contain"
            @click="faceDialogVisible = true"
          />
        </div>
      </el-form-item>
    </el-form>
    <div class="btns flex_end">
      <el-button size="large" type="primary" @click="submit(ruleFormRef)" v-show="type != 'detail'">确 定</el-button>
      <el-button size="large" type="danger" plain @click="handleClose">取 消</el-button>
    </div>

    <el-dialog 
      v-model="faceDialogVisible" 
      title="修改人脸信息"
      width="35%"
      destroy-on-close
    >
      <div style="position: relative;">
        <FaceEnter @confirm="confirmFace" :clearFaceBase="clearFaceBase" />
      </div>
      <el-button type="primary" @click="ensureEditFace" :disabled="hasFaceBase">确定录入</el-button>
      <el-button type="primary" @click="faceDialogVisible = false">取消</el-button>
    </el-dialog>
  </BasicDialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, toRefs, computed, inject } from 'vue';
import type { FormInstance, FormRules, UploadUserFile, UploadFile } from "element-plus";
import userApi from '@/request/api/user';
import { checkPhone } from "@/utils/util";
import { showMessageBox, showNotification } from "@/utils/alertMsg";

interface RuleForm {
  userid: number
  username: string
  avatar: any
  faceBase: any
  ismanager: number
  phone: string
  status: number
  createTime: string
  securityQ1: string
  securityQ2: string
  securityQ3: string
  securityA1: string
  securityA2: string
  securityA3: string
}

const ruleFormRef = ref<FormInstance>();

const ruleForm = reactive<RuleForm>({
  userid: 0,
  username: '',
  avatar: '',
  faceBase: '',
  ismanager: 0,
  phone: '',
  status: 0,
  createTime: '',
  securityQ1: '',
  securityQ2: '',
  securityQ3: '',
  securityA1: '',
  securityA2: '',
  securityA3: ''
});

// 刷新子路由
const reload: Function = inject("reload");

const validPhone = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入您的手机号"));
  } else if (!checkPhone(value)) {
    callback(new Error("手机号格式错误"));
  } else {
    callback();
  }
};

const rules = reactive<FormRules<RuleForm>>({
  userid: [{ required: true }],
  username: [
    { required: true, message: "请输入您的用户名", trigger: "blur" },
    { min: 3, max: 15, message: "长度必须在3-15个字符之间", trigger: "blur" },
  ],
  // avatar: [{ required: true, message: "" }],
  ismanager: [{ required: true }],
  status: [{ required: true }],
  createTime: [{ required: true }],
  faceBase: [{ required: true, message: "你必须录入人脸数据" }],
  phone: [{ validator: validPhone, required: true, trigger: "blur" }]
})

interface IOptionList {
  value: number
  label: string
}
/** 问题1 */
const options: Array<IOptionList> = [
  {
    value: 1,
    label: '启用'
  },
  {
    value: 0,
    label: '禁用'
  }
]

interface UserDialogProp {
  userDialogVisible: boolean
  title: string
  data: any
  type: '' | 'detail' | 'update'
}
const props = withDefaults(defineProps<UserDialogProp>(), {
  userDialogVisible: false,
  title: '',
  data: null,
  type: ''
});

const { userDialogVisible, data, type } = toRefs(props);

// 读取图像 获取源数据
function readImage(file: File) {
  const reader = new FileReader();
  let imageBinaryData: string | ArrayBuffer;
  reader.onload = function(e) {
    // 如果你需要获取原始图片的二进制数据，可以使用 reader.result
    imageBinaryData = reader.result;
    ruleForm.avatar = imageBinaryData;
  };
  reader.readAsDataURL(file);
}

const formLoading = ref<boolean>(false);
const OLD_ONE = 'old_avatar'
const fileList = ref<UploadUserFile[]>([])

const init = () => {
  formLoading.value = true;
  userApi.getUserDetail({
    userid: data.value.userid
  }).then((res: any) => {
    if(res.code == 200) {
      ruleForm.userid = res.data.userid;
      ruleForm.username = res.data.username;
      ruleForm.avatar = res.data.avatar;
      ruleForm.faceBase = res.data.faceBase;
      ruleForm.ismanager = res.data.ismanager;
      ruleForm.phone = res.data.phone;
      ruleForm.status = res.data.status;
      ruleForm.createTime = res.data.createTime;
      ruleForm.securityQ1 = res.data.securityQ1;
      ruleForm.securityQ2 = res.data.securityQ2;
      ruleForm.securityQ3 = res.data.securityQ3;
      ruleForm.securityA1 = res.data.securityA1;
      ruleForm.securityA2 = res.data.securityA2;
      ruleForm.securityA3 = res.data.securityA3;
      fileList.value.push({
        name: OLD_ONE,
        url: res.data.avatar
      })
    }
  }).finally(() => {
    formLoading.value = false;
  })
}
const handleRemove = (file: UploadFile) => {
  fileList.value.pop();
}
const handleChange = (file: UploadUserFile) => {
  readImage(file.raw);
}

let faceDialogVisible = ref<boolean>(false);
// 是否清除已拍照的图片
const clearFaceBase = ref<boolean>(false);
let imgFaceTarget = ref<any>();
const hasFaceBase = ref<boolean>(true);
// 录入人脸回调
const confirmFace = (model: any) => {
  // 表单赋值
  imgFaceTarget = model.faceBase;
  hasFaceBase.value = false;
};
const ensureEditFace = () => {
  ruleForm.faceBase = imgFaceTarget;
  faceDialogVisible.value = false;
}

onMounted(() => {
  init();
})

const isEdit = computed(() => {
  return type.value == "update";
})

// 提交表单
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // console.log('ruleForm:::', ruleForm)
      userApi.editUserByUserId(ruleForm).then((res: any) => {
        if(res.code == 200) {
          showNotification("success", "提示", res.msg);
          // 关闭弹窗
          handleClose();
          // 刷新子路由
          setTimeout(() => {
            reload();
          }, 200)
        } else {
          showNotification("error", "提示", res.msg);
        }
      })
    } else {
      console.log("error submit!", fields);
      showNotification("error", "提示", "验证未通过");
    }
  });
};


/**
 * defineEmits emit给父组件
 */
interface EmitEvent {
  (e: "handleClose"): void;
}
const emit = defineEmits<EmitEvent>();
const handleClose = () => {
  emit("handleClose");
};
</script>

<style scoped lang="scss">
.el-form-item {
  margin-bottom: 15px;
}
.el-select {
  width: 100%;
}
</style>